package com.z.xhelper.core.utils;

import com.z.xhelper.core.config.BeanContainer;
import com.z.xhelper.core.dao.WeChatMsg;

import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import de.robv.android.xposed.XposedHelpers;

public class HelperUtil {
    public static<T> JSONObject beanToJson(T t){
        JSONObject jsonObject = new JSONObject();
        // 反射获取字段
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true); // 设置私有字段可访问
                jsonObject.put(field.getName(),field.get(t));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    public static <T> String beanToJsonString(T t){
        return beanToJson(t).toString();
    }

    public static void hookSendTextMsg(WeChatMsg chatMsg){
        // hook 发送文本消息
        boolean result = false;
        try {
            ClassLoader classLoader = BeanContainer.getBean(ClassLoader.class);
            String receiveWxId = chatMsg.getTalker();
            String msg = chatMsg.getContent();
            Class<?> d0 = XposedHelpers.findClass("ie0.d0", classLoader);
            Method b = XposedHelpers.findMethodExact(d0, "b", String.class);
            Object b16 = b.invoke(null, receiveWxId);
            Class<?> f = XposedHelpers.findClass("ie0.d0.f", classLoader);
            Field d = XposedHelpers.findField(f, "d");
            d.set(b16, 1);
            XposedHelpers.setIntField(b16, "e", 0);
            Method g = XposedHelpers.findMethodExact(f, "g", String.class);
            g.invoke(b16, msg);
            Method j = XposedHelpers.findMethodExact(f, "j", String.class);
            j.invoke(b16, receiveWxId);
            Field g1 = XposedHelpers.findField(f, "g");
            g1.set(b16, null);
            Field h = XposedHelpers.findField(f, "h");
            h.set(b16, 5);
            Method a = XposedHelpers.findMethodExact(f, "a");
            Object a15 = a.invoke(b16);
            result = (boolean) XposedHelpers.callMethod(a15, "a");
            LogUtil.log( "发送文字消息返回值：" + result);
        } catch (Exception e) {
            LogUtil.log("发送文本失败" + e.toString());
        }
    }
}
